package com.hula.onion.book.server.spider.platforms.duoduolicai;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hula.onion.book.server.common.CommonResponse;
import com.hula.onion.book.server.common.SpiderCommon;
import com.hula.onion.book.server.config.ResponseStatusEnum;
import com.hula.onion.book.server.utils.HttpUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by work on 2018/1/29.
 */
@Component("duoDuoLiCaiSpider")
public class DuoDuoLiCaiSpider extends SpiderCommon {

    @Autowired
    private DuoDuoLiCaiSpiderHelper spiderHelper;

    private static final String LOGIN_URL = "https://www.51duoduo.com/ddlc/User/sign";

    private static  final String ACCOUNT_INFO="https://www.51duoduo.com/ddlc/PCPage/userInfo";

    @Override
    public CommonResponse execute() {
        String loginStr = HttpUtils.get(LOGIN_URL,
                spiderHelper.installRequestParams(loginForm), getHttpContext());
        if (StringUtils.isEmpty(loginStr)) {
            return new CommonResponse(ResponseStatusEnum.FAIL);
        }
        JSONObject loginJson = JSON.parseObject(loginStr);
        if ("3306".equals(loginJson.getString("code"))) {
            return new CommonResponse(ResponseStatusEnum.ACCOUNT_ERROR);
        }
        if ("0".equals(loginJson.getString("code"))) {
            Map<String,Object> params=new HashMap<>(1);
            params.put("?_",System.currentTimeMillis());
            String accountInfo=HttpUtils.get(ACCOUNT_INFO,params,getHttpContext());
            return spiderHelper.parseAccountBalance(accountInfo);
        }
        return new CommonResponse(ResponseStatusEnum.QUERY_FAIL);
    }
}
